import React, { PureComponent, Fragment } from 'react';

import { connect } from 'dva';

import moment from 'moment';

import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Badge, Divider, Radio } from 'antd';

import MyIcon from '@/components/MyIcon';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import StandardTableForm from '@/components/StandardTable/StandardTableForm';
import StandardTableHandle from '@/components/StandardTable/StandardTableHandle';

import { miniApps as tabList } from '@/commons/tabList';
import { usersApply as columns } from '@/commons/columns';
import { usersApply as map } from '@/commons/map';

// import lrzaa from 'lrz';

const FormItem = Form.Item;
const { TextArea } = Input;
const getValue = obj =>
  Object.keys(obj)
  .map(key => obj[key])
  .join(',');

const CreateForm = Form.create()(props => {
  const { modalVisible, queryRow = {}, form, handleUpdate, handleModalVisible } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleUpdate({ id: queryRow.id, ...fieldsValue });
    });
  };

  return (
    <Modal
      destroyOnClose
      width={300}
      title="标记为已审阅"
      visible={modalVisible}
      okText={queryRow.status && '更新'}
      okButtonProps={{}}
      onOk={okHandle}
      onCancel={handleModalVisible.bind(null,false)}
    >
      <FormItem labelCol={{ span: 24 }} wrapperCol={{ span: 24 }} label="备注（非必填）" style={{marginBottom: 0}}>
        {form.getFieldDecorator('remark', {
          initialValue: queryRow.remark,
          rules: [{ message: '请输入5~100个字符之间的备注内容！', min: 5, max: 100 }],
        })(<TextArea placeholder="请输入备注内容" autosize={{ minRows: 5, maxRows: 6 }} />)}
      </FormItem>
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({ apply, loading }) => ({
  apply,
  loading: loading.models.apply,
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    queryRow: {},
  };

  columns = [...columns, {
    title: '操作',
    width: 99,
    align: 'center',
    fixed: 'right',
    render: (queryRow = {}) => (
      <Button 
        icon="edit" 
        type="primary" 
        size="small"
        ghost={queryRow.status}
        onClick={this.handleModalVisible.bind(null, queryRow)}
      >
        {queryRow.status ? '已审阅' : '待审阅'}
      </Button>
    )
  }];

  componentDidMount() {
    const { dispatch } = this.props;

    dispatch({
      type: 'apply/fetch',
    });
  }

  handleTabChange = type => {
    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'apply/fetch',
      payload: { type }
    });
  }

  handleToggleTable = e => {
    e.preventDefault();

    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'apply/fetch',
      payload: { status: e.target.value }
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      from: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'apply/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'apply/fetch'
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'apply/remove',
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (!errno && data) {
              dispatch({
                type: 'apply/fetch'
              });
              this.setState({
                selectedRows: []
              });

              message.success(`共有${data}条申请已删除成功~`);
            } else {
              message.error('删除申请失败！');
            }
          },
        });
        break;
      case 'update':
        dispatch({
          type: 'apply/update',
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (errno) {
              message.error('已审阅失败！');
            } else {
              dispatch({
                type: 'apply/fetch'
              });
              this.setState({
                selectedRows: []
              });

              message.success(`共有${data}条申请已审阅成功~`);
            }
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState(state => ({
      ...state,
      selectedRows: rows,
    }));
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        createdAt: fieldsValue.createdAt && fieldsValue.createdAt.format('YYYY-MM-DD'),
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.format('YYYY-MM-DD'),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'apply/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = (queryRow = {}) => {
    const payload = {}

    if (isNaN(queryRow.id)) {
      Object.assign(payload, {
        modalVisible: false,
        queryRow: {}
      });
    } else {
      Object.assign(payload, {
        modalVisible: true,
        queryRow
      });
    }
    this.setState(state => ({
      ...state,
      ...payload
    }));
  };

  handleUpdate = (payload = {}) => {
    const { dispatch } = this.props;

    dispatch({
      type: 'apply/update',
      payload: { id: payload.id, remark: payload.remark },
      callback: ({ errno, data }) => {
        if (errno) {
          message.error('更新失败！');
        } else {
          dispatch({
            type: 'apply/fetch'
          });
          message.success(`序号${payload.id}的申请已审阅成功~`);
        }
      }
    });

    this.handleModalVisible();
  };

  // action={<a href="/favicon.png" target="_blank"><Button type="primary" icon="download">EXCEL</Button></a>}

  render() {
    const {
      apply: { data, type, status },
      loading,
      form,
    } = this.props;
    const { expandForm, queryRow, selectedRows, modalVisible } = this.state;

    const parentMethods = {
      queryRow,
      handleUpdate: this.handleUpdate,
      handleModalVisible: this.handleModalVisible,
    };
    return (
      <PageHeaderWrapper 
        title="上首页申请" 
        action={moment().format('LLLL')}
        tabList={tabList}
        tabActiveKey={String(type)}
        onTabChange={this.handleTabChange}
      >
        <Card bordered={false}>
          <StandardTableForm
            expandForm={expandForm}
            data={map}
            form={form}
            onSubmit={this.handleSearch}
            onReset={this.handleFormReset}
            onToggle={this.toggleForm}
          />
          <StandardTableHandle
            status={String(status)}
            radioGroups={{
              'all': <Fragment><MyIcon type="icon-all" />&nbsp;全部</Fragment>,
              '0': <Fragment><MyIcon type="icon-review" />&nbsp;待审阅</Fragment>,
              '1': <Fragment><MyIcon type="icon-preview" />&nbsp;已审阅</Fragment>,
            }}
            menuItems={{
              'remove': <Button type="danger" icon="delete" size="small" style={{width: '100%'}}>删除</Button>,
              'update': <Button type="primary" icon="edit" size="small" ghost style={{width: '100%'}}>已阅</Button>
            }}
            onToggleTable={this.handleToggleTable}
            onMenuClick={this.handleMenuClick}
          />
          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            scroll={{ x: 1500 }}
            columns={this.columns}
            expandedRowRender={record => <p style={{ marginBottom: 0 }}>备注：{record.remark}</p>}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
      </PageHeaderWrapper>
    );
  }
}

export default TableList;